package com.ruoyi.web.controller.shopping.address;

import com.ruoyi.system.domain.Address;
import com.ruoyi.system.domain.Area;
import com.ruoyi.system.service.AddressService;
import com.ruoyi.system.service.AreaService;
import com.ruoyi.system.view.common.R;
import com.ruoyi.web.controller.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/xiaomi/v2/address")
public class AddressController {
    @Autowired
    private AddressService addressService;

    @Autowired
    private AreaService areaService;

    @GetMapping("/list")
    public R<List<Address>> getList(HttpServletRequest request){
        String s = TokenUtil.userIdTokenCheck(request);
        List<Address> addressList = addressService.getAddressList(Integer.valueOf(s));
        return R.success(addressList);
    }

    @PostMapping
    public R<String> insertAddress(@RequestBody Address address,HttpServletRequest request){
        String s = TokenUtil.userIdTokenCheck(request);
//        System.out.println(address);
        address.setUserId(Integer.valueOf(s));
        address.setCreateBy(Integer.valueOf(s));
        address.setCreateTime(LocalDateTime.now());
        address.setUpdateBy(Integer.valueOf(s));
        address.setUpdateTime(LocalDateTime.now());
        for (Integer integer : address.getAreaArr()) {
            System.out.println(integer);
            Area areaById = areaService.getAreaById(integer);
            if (address.getArea().equals(null)){
                address.setArea(areaById.getName());
            }else {
                address.setArea(address.getArea()+" "+areaById.getName());
            }
        }
        addressService.insertAddress(address);
        return R.success("地址新增成功");
    }

    @DeleteMapping("/{addressId}")
    public R<String> deleteById(@PathVariable(value = "addressId") Integer addressId){
        addressService.deleteById(addressId);
        return R.success("删除成功");
    }
}
